package android.slc.icr.core.service.impl;

import android.slc.icr.core.entity.IcrUserInfo;
import android.slc.icr.core.service.IcrUserChartRoomService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 简单的用户存在的房间服务
 * 这里面的信息没有进行持久化
 * @author slc
 * @date 2022/05/11 下午 2:04
 */
public class SimpleIcrUserChartRoomService implements IcrUserChartRoomService {
    private static class Holder {
        private final static SimpleIcrUserChartRoomService simpleUserChartRoomService = new SimpleIcrUserChartRoomService();
    }

    public static SimpleIcrUserChartRoomService getInstance() {
        return Holder.simpleUserChartRoomService;
    }

    /**
     * 用户所在房间的信息，key为用户，value为与该用户有关的房间的用户自己的信息，通过此集合可以知道用户，在哪些房间，哪些房间室友用户创建的
     */
    private final Map<String, List<IcrUserInfo>> userAssociateRoomMap = new ConcurrentHashMap<>();

    @Override
    public void attachUserByRoom(IcrUserInfo icrUserInfo) {
        List<IcrUserInfo> userAssociateRoomList = userAssociateRoomMap.computeIfAbsent(icrUserInfo.getUserId(), k -> new ArrayList<>());
        if (!userAssociateRoomList.contains(icrUserInfo)) {
            userAssociateRoomList.add(icrUserInfo);
        }
    }

    @Override
    public void detachUserByRoom(IcrUserInfo icrUserInfo) {
        List<IcrUserInfo> userAssociateRoomList = userAssociateRoomMap.get(icrUserInfo.getUserId());
        if (userAssociateRoomList != null) {
            userAssociateRoomList.remove(icrUserInfo);
        }
    }

    @Override
    public List<IcrUserInfo> findByUserId(String userId) {
        return userAssociateRoomMap.get(userId);
    }
}
